package com.example.footclassfiydome.service;

import ai.djl.MalformedModelException;
import ai.djl.Model;
import ai.djl.inference.Predictor;
import ai.djl.modality.Classifications;
import ai.djl.modality.cv.Image;
import ai.djl.modality.cv.ImageFactory;
import ai.djl.modality.cv.transform.Resize;
import ai.djl.modality.cv.transform.ToTensor;
import ai.djl.modality.cv.translator.ImageClassificationTranslator;
import ai.djl.translate.TranslateException;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.nio.file.Paths;

/**
 * Created by lilijava
 * on 2024/12/25
 * <p>
 * on  foot-classfiy-dome
 */
@Service
public class InterfenceService {
    public Classifications predict(String ImagePath) throws IOException {
        Image image=ImageFactory.getInstance().fromFile(Paths.get(ImagePath));
        Classifications result;
        try (Model model = Models.getModel()){
            model.load(Paths.get("build/models"));
            ImageClassificationTranslator translator = ImageClassificationTranslator.builder()
                    .addTransform(new Resize(100, 100))
                    .addTransform(new ToTensor())
                    .optApplySoftmax(true)
                    .build();
            try (Predictor<Image, Classifications>predictor=model.newPredictor(translator)){
                result=predictor.predict(image);
            } catch (TranslateException e) {
                throw new RuntimeException(e);
            }

        } catch (MalformedModelException | IOException e) {
            throw new RuntimeException(e);
        }
        return result;
    }

}
